/*
 * Copyright (C) 2011 Chris Gao <chris@exina.net>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.hcb.tonguetiphealth.view;

import java.util.Calendar;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.text.format.DateUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.hcb.tonguetiphealth.manager.DBManager;

/**
 * Android日期控件修正版
 * @Description: 可以选择上，下月，可以显示选择的日期。

 * @FileName: CalendarActivity.java 

 * @Package com.exina.android.calendar 

 * @Author Hanyonglu

 * @Date 2012-3-26 上午11:36:05 

 * @Version V1.0
 */
public class CalendarActivity extends Activity  implements CalendarView.OnCellTouchListener{
	public static final String MIME_TYPE = "vnd.android.cursor.dir/vnd.exina.android.calendar.date";
	private CalendarView mView = null;
	private Handler mHandler = new Handler();
	private  Button btCenter;
	private Rect ecBounds;
	
	private Button btSave;
	private Button btEdit;
	private Button btCommit, btDel;
	private EditText etPlan;
	private String userId;
	private DBManager db;
	private String date;
	
	public static Cell currentCell;
	
	private Activity ctx;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.homepage_plan);
        currentCell = null;
        mView = (CalendarView)findViewById(R.id.calendar);
        mView.setOnCellTouchListener(this);
        ctx = this;
        db =  DBManager.getInstance(ctx);
        userId = getIntent().getStringExtra("userId");
        bindEvent();
        //new BottomWidget(ctx);
        btCenter = (Button) findViewById(R.id.btCenter);
        btCenter.setText(mView.getYear() + "-" + (mView.getMonth() + 1));
        Button btLeft = (Button) findViewById(R.id.btnLeft);
        btLeft.setText("上月");
        Button btRight = (Button) findViewById(R.id.btRight);
        btRight.setText("下月");
        btLeft.setOnClickListener(new OnClickListener() { 
			public void onClick(View v) {
				currentCell = null;
				etPlan.setText("");
				mView.previousMonth(); 
				setTodayPlan(mView.getYear(), mView.getMonth());
				btCenter.setText(mView.getYear() + "-" + (mView.getMonth() + 1));
			}
		});
        btRight.setOnClickListener(new OnClickListener() { 
			public void onClick(View v) {
				currentCell = null;
				etPlan.setText("");
				mView.nextMonth(); 
				setTodayPlan(mView.getYear(), mView.getMonth());
				btCenter.setText(mView.getYear() + "-" + (mView.getMonth() + 1));
			}
		});
        
    }

    private void setTodayPlan(int year, int month){
    	Calendar calendar = Calendar.getInstance();
    	System.out.println("year"+year+"month"+month);
    	date = calendar.get(Calendar.YEAR) + "-" +calendar.get(Calendar.MONTH) + "-" + calendar.get(Calendar.DAY_OF_MONTH);
    	System.out.println("date"+date);
    	if (year == calendar.get(Calendar.YEAR) && month == calendar.get(Calendar.MONTH)) {
    	    
			etPlan.setText(getPlan());
		}
    }
    
    private void bindEvent(){
    	btSave = (Button)findViewById(R.id.homepage_plan_save);
     //   btEdit = (Button)findViewById(R.id.homepage_plan_edit);
        btCommit = (Button)findViewById(R.id.homepage_plan_commit);
        btDel = (Button)findViewById(R.id.homepage_plan_del);
        etPlan = (EditText)findViewById(R.id.homepage_plan_et);
        Calendar calendar = Calendar.getInstance();
        date = calendar.get(Calendar.YEAR) + "-" +calendar.get(Calendar.MONTH) + "-" + calendar.get(Calendar.DAY_OF_MONTH);
       
        etPlan.setText(getPlan());
        
        btSave.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String plan = etPlan.getText().toString().trim();
				if (plan == null || plan.equals("")) {
					Toast.makeText(ctx, "计划不能为空!", Toast.LENGTH_LONG).show();
					return;
				}
				savePlan(plan);
				btDel.setVisibility(View.VISIBLE);
			}
		});
        
//        btEdit.setOnClickListener(new OnClickListener() {
//			
//			@Override
//			public void onClick(View v) {
//				// TODO Auto-generated method stub
//				etPlan.setEnabled(true);
//			}
//		});
        btCommit.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
			}
		});
        btDel.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				delPlan();
				btDel.setVisibility(View.GONE);
			}
		});
    }
    
    private void delPlan(){
    	
    	Cursor cursor = db.getCursor(true, DBManager.table_plan, null, "usrid='"+ userId+"' and plandate='" +date+"'",null,null,null,null,null);
    	int count = cursor.getCount();
    	
    	if (count > 0) {
    		cursor.moveToFirst();
    		String id = cursor.getString(0);
    		db.delete(DBManager.table_plan, id);
    		etPlan.setText("");
    	}
    }
    
    private void savePlan(String strPlan){
    	//保存到数据库
    	Cursor cursor = db.getCursor(true, DBManager.table_plan, null, "usrid='"+ userId+"' and plandate='" +date+"'",null,null,null,null,null);
    	int count = cursor.getCount();
    	ContentValues values = new ContentValues();
		values.put("usrid", userId);
		values.put("plan", strPlan);
		values.put("plandate", date);
		
    	if (count > 0) {
    		cursor.moveToFirst();
    		String id = cursor.getString(0);
    		cursor.close();
    		boolean b = db.update(DBManager.table_plan, id, values);
    	//	System.out.println("更新失败or成功"+b);
    		
			//更新
		}else {
			//添加
			cursor.close();
		  long id = db.insert(DBManager.table_plan, values);
		//  System.out.println("插入成功:"+id);
		}
    }
    
    private String getPlan(){
    	String plan = "";
    	Cursor cursor = db.getCursor(true, DBManager.table_plan, null, "usrid='"+ userId+"' and plandate='"+date+"'",null,null,null,null,null);
    	if (cursor.getCount() >0) {
			cursor.moveToFirst();
			plan = cursor.getString(2);
			cursor.close();
			btDel.setVisibility(View.VISIBLE);
		}else {
			btDel.setVisibility(View.GONE);
		}
    	return plan;
    }
    
	public void onTouch(Cell cell) {
		
		if(cell.mPaint.getColor() == Color.GRAY) {
			// 这是上月的
			currentCell = null;
			mView.previousMonth(); 
			btCenter.setText(mView.getYear() + "-" + (mView.getMonth() + 1));
		} else if(cell.mPaint.getColor() == Color.LTGRAY) {
			// 下月的
			currentCell = null;
			mView.nextMonth(); 
			btCenter.setText(mView.getYear() + "-" + (mView.getMonth() + 1));
		} else {  //  本月的
				currentCell = cell;
				Intent ret = new Intent();
				ret.putExtra("year", mView.getYear());
				ret.putExtra("month", mView.getMonth());
				ret.putExtra("day", cell.getDayOfMonth());
				System.out.println("当前日期：" + mView.getYear() + "-" + mView.getMonth() + "-" + cell.getDayOfMonth());
				// 在此让当前的View 重绘一次
				date = mView.getYear() + "-" + mView.getMonth() + "-" + cell.getDayOfMonth();//日期格式2013-4-3
				ecBounds = cell.getBound();
				mView.getDate();
//				MyCalendarView mCalendarView = new MyCalendarView(CalendarActivity.this);
//				mCalendarView  =  (MyCalendarView) mView;
				mView.mDecoraClick.setBounds(ecBounds);
				mView.invalidate();
				etPlan.setText(getPlan());
//				this.setResult(RESULT_OK, ret);
//				finish();
				return;
		}
//		int day = cell.getDayOfMonth();
//		if(mView.firstDay(day))
//			mView.previousMonth();
//		else if(mView.lastDay(day))
//			mView.nextMonth();
//		else
//			return;

		mHandler.post(new Runnable() {
			public void run() {
				btCenter.setText(mView.getYear() + "-" + (mView.getMonth() + 1));
				Toast.makeText(CalendarActivity.this, DateUtils.getMonthString(mView.getMonth(), DateUtils.LENGTH_LONG) + " "+mView.getYear(), Toast.LENGTH_SHORT).show();
			}
		});
	}
 
}